package com.tnl.hunter.webchat.controller;

import com.alibaba.fastjson.JSON;
import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.qq.wechat.api.MediaAPI;
import com.biz.qq.wechat.entity.jsConfig;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.DateUtil;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.tnl.hunter.webchat.utils.ListParam;
import com.tnl.hunter.webchat.utils.RecoParam;
import com.tnl.hunter.webchat.utils.SMSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class MyRecommendController {

    private static final Logger logger = LoggerFactory
            .getLogger(MyRecommendController.class);

    @Autowired
    private WXUserDAO userDAO;
    @Autowired
    private RecommendDAO recommendDAO;
    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private PersonDAO personDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private InterViewDAO interviewDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private JobTitleDAO roleDAO;
    @Autowired
    private SysConfigRepo sysConfigService;
    @Autowired
    private EmployerDAO employerDAO;
    @Autowired
    private EmployeeDAO employeeDAO;

    /* 分享平台 */
    /*
     * @OAuthRequired
     *
     * @RequestMapping(value = "wechat/headhunter/recommend/share.page", method
     * = RequestMethod.GET) public String share(HttpServletRequest request,
     * Model model) { // 方案一 生成场景二维码，获取二维码，显示在 // String openID =
     * request.getParameter("openid"); // 分享 ****************接受 // 方案二 直接调用js
     * 调用微信分享接口 HttpSession session = request.getSession(); String openid =
     * (String) session.getAttribute("OpenId"); logger.debug("openid is " +
     * openid); //String token = sysConfigService.getAccessToken(); String
     * ticket = systemConfigRepo.getJsTicket();
     * logger.debug("js api ticket is "+ticket);
     *
     * //String url =
     * "http://www.tiaonali.com/wechat/headhunter/recommend/share.page"; String
     * url = request.getRequestURL().toString(); logger.debug("request url is "
     * + url); Map<String, String> jsconfig = SignUtil.getJSSignature(ticket,
     * url);
     *
     * model.addAttribute("appid", WebchatServiceConstant.APPID);
     * model.addAttribute("currenttimestamp", jsconfig.get("timestamp"));
     * model.addAttribute("nonceStr", jsconfig.get("nonceStr"));
     * model.addAttribute("signatureStr", jsconfig.get("signature"));
     *
     * return "wechat/headhunter/recommend/shareme"; }
     */

    // ==============菜单入口：我的推荐(猎头)
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/recommend/main.page", method = RequestMethod.GET)
    public String recommendation(HttpServletRequest request, ModelMap model) {
        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
//        openid="o852Is7CAaACPsK06dWq5NUKlC-o";
//        openid="o852Iszmo-oB1bhEPnzVdKTmsBxA";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            if (hunter.getBinded() != 1) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
                return "wechat/headhunter/msgpage";
            }
            List<RecommendPosition> list = recommendDAO
                    .getRecommendPositionByCreater(1, hunter.getId(), 1, offset);

            if (list != null) {
                for (RecommendPosition recommend : list) {
                    int jobid = recommend.getJobid();
                    int createrid = recommend.getCreateby();
                    long time = recommend.getExpiredDate();
                    Date date = new Date(time);
                    SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String str = bartDateFormat.format(date);
                    recommend.setExpiredDateStr(str);
                    List<RecommendedPerson> plist = recommendDAO
                            .getRecommendedPersonByPositionAndCreater(1,
                                    createrid, 1, jobid, 0);
                    recommend.setRecommendedPerson(plist);
                }
            } else {
                list = new ArrayList<RecommendPosition>();
            }

            model.addAttribute("recommends", list);

            /* */
            String ticket = sysConfigService.getJsTicket();
            logger.debug("js api ticket is " + ticket);
            String url = request.getRequestURL().toString();
            if (!StringUtils.isEmpty(request.getQueryString())) {
                url = url + "?" + request.getQueryString();
            }
            logger.debug("request url is " + url);

            Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

            jsConfig config = new jsConfig();
            config.setAppid(WebchatServiceConstant.APPID);
            config.setCurrenttimestamp(jsconfig.get("timestamp"));
            config.setNonceStr(jsconfig.get("nonceStr"));
            config.setSignatureStr(jsconfig.get("signature"));

            model.addAttribute("config", config);
            /* */

            return "wechat/headhunter/recommend/zhiweizhuangtailiebiao";
        }
    }

    // 更多我的推荐(猎头)
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/recommend/moreRecommend.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> moreRecommendation(HttpServletRequest request,
                                           ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
//        openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
//        openid = "o852Iszmo-oB1bhEPnzVdKTmsBxA";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们的服务");
            return returnMap;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }
        // offset = 0;

        List<RecommendPosition> list = recommendDAO
                .getRecommendPositionByCreater(1, hunter.getId(), 1, offset);

        list.parallelStream().map(recommend->{
            int jobId = recommend.getJobid();
            int createId = recommend.getCreateby();

            List<RecommendedPerson> plist = recommendDAO
                    .getRecommendedPersonByPositionAndCreater(1, createId,
                            1, jobId, 0);
            recommend.setRecommendedPerson(plist);
            return recommend;
        }).collect(Collectors.toList());

        returnMap.put("errorcode", 0);
        returnMap.put("msg", "成功获取数据");
        returnMap.put("recommends", list);
        logger.info(JSON.toJSONString(list));

        return returnMap;
    }

    // 职位候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/recommend/toView.do", method = RequestMethod.GET)
    public String searchJobs(HttpServletRequest request, Integer jobid,
                             ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
//        openid ="o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/candidate/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证，但此处不需要有继续功能
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        List<RecommendedPerson> list = recommendDAO
                .getRecommendedPersonByPositionAndCreater2(2, hunter.getId(),
                        jobid, 0);
        for (RecommendedPerson recommendedPerson : list) {
            if (!StringUtils.isEmpty(recommendedPerson.getCityId())) {
                City city = cityDAO.getById(Integer.parseInt(recommendedPerson.getCityId()));
                recommendedPerson.setCityName(city.getName());
            }
        }
        JobDesc job = jobDAO.getById(jobid);
        Company company = companyDAO.getById(job.getCompanyId());

        model.addAttribute("job", job);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/zhiweihouxuanrenliebiao";
    }

    // 更多职位候选人信息
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/recommend/moreRecommend2.do", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> moreRecommendation2(HttpServletRequest request,
                                            ModelMap model) {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            returnMap.put("errorcode", -1);
            returnMap.put("msg", "您尚未关注我们");
            return returnMap;
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            returnMap.put("errorcode", -2);
            returnMap.put("msg", "您尚未注册我们的服务");
            return returnMap;
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        } else {
            offset = Integer.valueOf(startStr);
        }
        // offset = 0;

        Integer jobid = Integer.valueOf(request.getParameter("jobid"));
        if (StringUtils.isEmpty(jobid)) {
            returnMap.put("errorcode", -3);
            returnMap.put("msg", "未指定职位");
            return returnMap;
        }

        List<RecommendedPerson> list = recommendDAO
                .getRecommendedPersonByPositionAndCreater2(2, hunter.getId(),
                        jobid, offset);
        JobDesc job = jobDAO.getById(jobid);
        Company company = companyDAO.getById(job.getCompanyId());

        returnMap.put("errorcode", 0);
        returnMap.put("msg", "成功获取数据");
        returnMap.put("recommends", list);
        returnMap.put("job", job);
        returnMap.put("company", company);

        return returnMap;
    }

    // =====================菜单入口 ： 悬赏职位
    // 显示职位信息，并从这里开始推荐
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/jobdetail.page", method = RequestMethod.GET)
    public String viewJobDetail(HttpServletRequest request, int id,
                                ModelMap model) {

        HttpSession session = request.getSession();

        // 调试用，正式发布前要注释掉
        // session.setAttribute("OpenId", "123");

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.error("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证，但此处不需要有继续功能
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */
            model.addAttribute("msg", "你尚未注册我们的服务，点击继续注册你的信息。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        JobDesc job = jobDAO.getById(id);
        if (job == null) {
            logger.info("invalid Job id " + id);
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "该职位并不存在。");
            return "wechat/headhunter/msgpage";
        }

        int companyId = job.getCompanyId();
        int cityId = job.getCityId();
        Company company = companyDAO.getById(companyId);
        City city = cityDAO.getById(cityId);

        job.setCity(city);
        if (company != null) {
            job.setCompanyName(company.getName());
        }
        long data = job.getExpiredDate();
        job.setExpiredDateStr(DateUtil.getDateStr(data));
        model.addAttribute("job", job);

        List<Company> companies = companyDAO.getALL();
        model.addAttribute("companies", companies);
        List<City> cities = cityDAO.getALL();
        model.addAttribute("cities", cities);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/hunter/zhiweixinxi";
    }

    // 2017-7-14推荐他人列表,猎头曾经推荐过的候选人信息显示
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/toRecommedList.do", method = RequestMethod.GET)
    public String toRecommendList(HttpServletRequest request, Integer jobId, ModelMap model) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }

        int offset = 0;
        String startStr = request.getParameter("offset");
        if (StringUtils.isEmpty(startStr)) {
            offset = 0;
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        } else {
            if (hunter.getBinded() != 1) {
                model.addAttribute("title", "信息审核中");
                model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
                return "wechat/headhunter/msgpage";
            }
            List<RecommendPosition> list = recommendDAO
                    .getRecommendPositionByCreater(2, hunter.getId(),1, offset);
            int initNum = 0;
            if (list != null && list.size() != 0) {
                for (RecommendPosition recommend : list) {
                    int jobid = recommend.getJobid();
                    int createrid = recommend.getCreateby();

                    List<RecommendedPerson> plist = recommendDAO
                            .getRecommendedPersonByPositionAndCreater(2,
                                    createrid, 1, jobid, 0);
                    initNum += plist == null ? 0 : plist.size();
                    recommend.setRecommendedPerson(plist);
                }
            } else {
                list = new ArrayList<RecommendPosition>();
                List<Company> companies = companyDAO.getALL();
                List<City> cities = cityDAO.getALL();
                List<JobTitle> roles = roleDAO.getALL();
                model.addAttribute("companies", companies);
                model.addAttribute("roles", roles);
                model.addAttribute("jobId", jobId);
                model.addAttribute("cities", cities);
                return "wechat/headhunter/houxuanrenjianli";
            }

            model.addAttribute("initNum", initNum);
            model.addAttribute("jobId", jobId);
            model.addAttribute("recommends", list);

            /* */
            String ticket = sysConfigService.getJsTicket();
            logger.debug("js api ticket is " + ticket);
            String url = request.getRequestURL().toString();
            if (!StringUtils.isEmpty(request.getQueryString())) {
                url = url + "?" + request.getQueryString();
            }
            logger.debug("request url is " + url);

            Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

            jsConfig config = new jsConfig();
            config.setAppid(WebchatServiceConstant.APPID);
            config.setCurrenttimestamp(jsconfig.get("timestamp"));
            config.setNonceStr(jsconfig.get("nonceStr"));
            config.setSignatureStr(jsconfig.get("signature"));

            model.addAttribute("config", config);
            /* */

            return "wechat/headhunter/recommend/candidateliebiao";
        }
    }

    // 依据手机号是否在DB库有过推荐，直接导入
/*	@OAuthRequired
	@RequestMapping(value = "wechat/headhunter/recommandValPhone.page", method = RequestMethod.GET)
	public String viewRecommandValPhone(HttpServletRequest request,Integer jobId, ModelMap model) {
		HttpSession session = request.getSession();

		String openid = (String) session.getAttribute("OpenId");
		logger.debug("openid is " + openid);
		if (!StringUtils.isEmpty(openid)) {
			model.addAttribute("openid", openid);
		}
		model.addAttribute("jobId", jobId);
		
		return "wechat/headhunter/recommend/candidateValPhone";
	}*/
    //Integer jobId,Integer personId

    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/batchRecommend.do", method = RequestMethod.POST)
    public String batchRecommend(HttpServletRequest request, ListParam param, Integer[] checkedId, ModelMap model) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您尚未关注我们");
            return "wechat/headhunter/msgpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您尚未关注我们");
            return "wechat/headhunter/msgpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您尚未注册我们");
            return "wechat/headhunter/msgpage";
        }
        List<RecoParam> recs = param.getRecs();
        if (recs == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "您尚未关注我们");
            return "wechat/headhunter/msgpage";
        }
        if (checkedId == null) {
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "请选择候选人");
            return "wechat/headhunter/msgpage";
        }
        List<RecoParam> recList = new ArrayList<RecoParam>();
        for (RecoParam temp : recs) {
            for (Integer id : checkedId) {
                if (temp.getRecId().toString().equals(id.toString())) {
                    recList.add(temp);
                }
            }
        }

        if (recList.size() == 1) {
            RecoParam temp = recList.get(0);
            List<Company> companies = companyDAO.getALL();
            List<City> cities = cityDAO.getALL();
            List<JobTitle> roles = roleDAO.getALL();
            Person person = personDAO.getById(temp.getPersonId());
            model.addAttribute("companies", companies);
            model.addAttribute("roles", roles);
            model.addAttribute("jobId", temp.getJobId());
            model.addAttribute("cities", cities);
            model.addAttribute("employee", person);
            return "wechat/headhunter/houxuanrenjianli";
        }
        for (RecoParam rec : recList) {
            // 检查（根据手机号码、候选人姓名）检查该人是否已经被推荐该职位
            List<Recommendation> list = null;
            list = recommendDAO.getByJobAndPhone(rec.getJobId(), rec.getPhone(), 0);

            if (list != null && list.size() > 0) {
                model.addAttribute("title", "温馨提示");
                model.addAttribute("msg", rec.getName() + "此候选人已经被推荐给该职位");
//					return "wechat/headhunter/msgpage";
            }

            Recommendation recommend = new Recommendation();
            recommend.setJobId(rec.getJobId());
            recommend.setReason("系统默认推荐");
            recommend.setPlatformId(2);
            recommend.setCreateby(hunter.getId());
            Person candidate = new Person();
            candidate.setName(rec.getName());
            candidate.setAge(rec.getAge());
            candidate.setWorkage(rec.getWorkage());
            candidate.setPhone(rec.getPhone());
            candidate.setRoleId(rec.getRoleId());
            // candidate.setCompanyId(dto.getCompanyId());
            candidate.setInservice(rec.getInservice());
            candidate.setCityId(rec.getCityId());
            if (StringUtils.isEmpty(rec.getCityId())) {
                City city = cityDAO.getById(rec.getCityId());
                candidate.setCityName(city.getName());
            }
            String companyname = rec.getCompanyName();
            if (StringUtils.isEmpty(companyname)) {
                model.addAttribute("title", "温馨提示");
                model.addAttribute("msg", "必须提交公司信息");
                return "wechat/headhunter/msgpage";
            }
            Company company = new Company();
            company = companyDAO.getByName(companyname);
            if (company == null) {
                candidate.setCompanyId(0);
                candidate.setCompanyName(companyname);
            } else {
                candidate.setCompanyId(company.getId());
                candidate.setCompanyName(company.getName());
            }
            candidate.setId(rec.getPersonId());
            int personId = personDAO.update(candidate);

            if (personId == -1) {
                logger.error("can not create the candidate " + candidate);
                model.addAttribute("msg", "操作出错");
                return "wechat/headhunter/errorpage";
            }
            recommend.setPersonId(rec.getPersonId());
            Date now = new Date();
            recommend.setCreateDate(now.getTime());

            // 创建推荐信息
            int id = recommendDAO.save(recommend);
            if (id == -1) {
                logger.error("can not create Recommendation " + candidate);
                model.addAttribute("msg", "操作出错");
                return "wechat/headhunter/errorpage";
            }
        }

        return "wechat/headhunter/recommend/recommandhouxuanqueren";

    }

    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/existPhone.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> isExistPhone(HttpServletRequest request, String phone, ModelMap model) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (!StringUtils.isEmpty(openid)) {
            model.addAttribute("openid", openid);
        }
        EmployeePerson emp = employeeDAO.existPhone(phone);
        if (emp == null) {

            logger.error("success to save the hunter " + emp);
            returnMap.put("errorcode", "0");
            returnMap.put("msg", "此手机号不存在系统内,请创建新的的候选人简历！");

            return returnMap;
        } else {
            logger.error("fail to save the hunter " + emp);
            returnMap.put("errorcode", "1");
            returnMap.put("msg", "此手机号已存在系统内，候选人已被推荐过！");

            return returnMap;
        }

    }


    // 推荐他人(填写候选人的信息)
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/toRecommend.do", method = RequestMethod.GET)
    public String toRecommend(HttpServletRequest request, Integer jobId, Integer personId,
                              ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
//        openid= "o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.error("openid is null");
            return "wechat/hunter/main.page";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }
        if (hunter.getBinded() != 1) {
            model.addAttribute("title", "信息审核中");
            model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
            return "wechat/headhunter/msgpage";
        }

        List<Company> companies = companyDAO.getALL();
        List<City> cities = cityDAO.getALL();
        List<JobTitle> roles = roleDAO.getALL();
        if (!StringUtils.isEmpty(personId)) {
            Person person = personDAO.getById(personId);
            model.addAttribute("employee", person);
        }
        model.addAttribute("companies", companies);
        model.addAttribute("roles", roles);
        model.addAttribute("jobId", jobId);
        model.addAttribute("cities", cities);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        return "wechat/headhunter/houxuanrenjianli";
    }

    // 保存推荐信息，做必要的检查
    @OAuthRequired
    @ResponseBody
    @RequestMapping(value = "wechat/headhunter/recommend/recommend.do", method = RequestMethod.POST)
    public Map<String, Object> recommend(HttpServletRequest request,
                                         RecommendDTO dto, ModelMap model) {
        Map<String, Object> msg = new HashMap<String, Object>();

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
//        openid="o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            msg.put("errorcode", -1);
            msg.put("msg", "您尚未关注我们");
            return msg;
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            msg.put("errorcode", -2);
            msg.put("msg", "您尚未注册我们");
            return msg;
        }

        // 检查（根据手机号码、候选人姓名）检查该人是否已经被推荐该职位
        List<Recommendation> list = null;
        list = recommendDAO.getByJobAndPhone(dto.getJobId(), dto.getPhone(), 2);

        if (list != null && list.size() > 0) {
            msg.put("errorcode", -3);
            msg.put("msg", "此候选人已经被推荐给该职位");
            return msg;
        }

        Recommendation recommend = new Recommendation();
        recommend.setJobId(dto.getJobId());
        recommend.setReason(dto.getReason());
        recommend.setPlatformId(1); //原来为2，因为直通车候选人沟通申请，会因此过滤掉2的推荐。所以不分平台，改为1
        recommend.setRefereeType(1); // 1 为猎头推荐 非1 的是自己推荐或者HR
        recommend.setCreateby(hunter.getId());
        City city = cityDAO.getById(dto.getCityId());
        JobTitle jobTitle = roleDAO.getById(dto.getRoleId());
        Person person = personDAO.getByPhone(dto.getPhone());
        if (person != null) {
            person.setCreateby(hunter.getId());
            recommend.setPersonId(person.getId());
            person.setName(dto.getName());
            person.setPhone(dto.getPhone());
            person.setRoleId(dto.getRoleId());
            JobTitle byId1 = roleDAO.getById(dto.getRoleId());
            if (byId1 != null) {
                person.setRoleName(byId1.getName());
            }
            person.setCityId(dto.getCityId());
            if (!Objects.isNull(city)) {
                person.setCityName(city.getName());
            }
            if (!Objects.isNull(jobTitle)) {
                person.setRoleName(jobTitle.getName());
            }


            City byId = cityDAO.getById(dto.getCityId());
            if (byId != null) {
                person.setCityName(byId.getName());
            }
            person.setAge(dto.getAge());
            person.setWorkage(dto.getWorkage());
            person.setInservice(dto.getInservice());
            String companyname = dto.getCompanyName();
            if (StringUtils.isEmpty(companyname)) {
                msg.put("errorcode", -3);
                msg.put("msg", "必须提交公司信息");
                return msg;
            }
            Company company = companyDAO.getByName(companyname);
            if (company == null) {
                person.setCompanyId(0);
                person.setCompanyName(companyname);
            } else {
                person.setCompanyId(company.getId());
                person.setCompanyName(company.getName());
            }
            personDAO.updateCandidate(person);

        } else {
            Person candidate = new Person();
            candidate.setCreateby(hunter.getId());
            candidate.setName(dto.getName());
            candidate.setPhone(dto.getPhone());
            candidate.setRoleId(dto.getRoleId());

            candidate.setCityId(dto.getCityId());
            candidate.setAge(dto.getAge());
            candidate.setWorkage(dto.getWorkage());
            candidate.setInservice(dto.getInservice());
            if (!Objects.isNull(city)) {
                candidate.setCityName(city.getName());
            }
            if (!Objects.isNull(jobTitle)) {
                candidate.setRoleName(jobTitle.getName());
            }
            String companyname = dto.getCompanyName();
            if (StringUtils.isEmpty(companyname)) {
                msg.put("errorcode", -3);
                msg.put("msg", "必须提交公司信息");
                return msg;
            }


            Company company = companyDAO.getByName(companyname);
            if (company == null) {
                candidate.setCompanyId(0);
                candidate.setCompanyName(companyname);
            } else {
                candidate.setCompanyId(company.getId());
                candidate.setCompanyName(company.getName());
            }

            int personId = personDAO.save(candidate);

            if (personId == -1) {
                logger.error("can not create the candidate " + candidate);
                msg.put("errorcode", -4);
                msg.put("msg", "操作出错");
                return msg;
            }
            recommend.setPersonId(personId);
        }


        Date now = new Date();
        recommend.setCreateDate(now.getTime());

        // 创建推荐信息
        int id = recommendDAO.save(recommend);
        if (id == -1) {
            logger.error("can not create Recommendation personcandidate");
            msg.put("errorcode", -4);
            msg.put("msg", "操作出错");
            return msg;
        }
        JobDesc jobDesc = jobDAO.getById(dto.getJobId());
        Employer employer = employerDAO.getById(jobDesc.getCreatedby());
        if (employer != null){
            String tempjsonhunter = TemplateData.New()
                    .setTouser(employer.getOpenid())
                    .setTemplate_id("IFTCljrBeL4Ef8alZUDQlZqwLafadkX5APawYS4K4_U")
                    //.setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/toViewCandidate.do?jobid="+jobdesc.getId()+"&empid="+person.getId()+"&recommendid="+recommendmeId)
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/toInterview.do?recommendid=" + id)
                    .add("first", "您有一份新的简历，请及时查阅", "#274084")
                    .add("keyword1", jobDesc.getName(), "#000000")
                    .add("keyword2", person.getName(), "#F47e2d")
                    .add("keyword3", person.getWorkage().toString(), "#000000")
                    .add("remark", "请点击查看详情", "#274084")
                    .build();
            System.out.println(tempjsonhunter);
            ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
            System.out.println("模板消息发送结果：" + reshunter);
        }


        msg.put("errorcode", 0);
        msg.put("msg", "获取数据成功");
        msg.put("recommendId", id);
        return msg;
    }

    // 推荐确认，上传简历
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/toConfirm.page", method = RequestMethod.GET)
    public String showConfirmPage(HttpServletRequest request,
                                  String recommendId, ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证，但不需要继续
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */

            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        Recommendation rd = recommendDAO.getById(recommendId);
        if (rd == null) {
            logger.error("can't find the Recommendation with the id "
                    + recommendId);
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "提供的信息不对");
            return "wechat/headhunter/msgpage";
        }

        int personId = rd.getPersonId();
        int jobId = rd.getJobId();
        Person person = personDAO.getById(personId);
        if (person == null) {
            logger.error("can't find the person with the id " + personId);
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "提供的信息不对");
            return "wechat/headhunter/msgpage";
        }

        JobDesc job = jobDAO.getById(jobId);
        if (job == null) {
            logger.error("can't find the job that the id is " + jobId);
            model.addAttribute("title", "温馨提示");
            model.addAttribute("msg", "提供的信息不对");
            return "wechat/headhunter/msgpage";
        }
        // String token = sysConfigService.getAccessToken();
        // JSTicket ticket = JSTicketAPI.getJsTicket(token);
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);

        model.addAttribute("personName", person.getName());
        model.addAttribute("jobName", job.getName());
        model.addAttribute("jobReward", job.getReward());
        model.addAttribute("recommendid", recommendId);

        return "wechat/headhunter/houxuanrenqueren";
    }

    // 上传简历
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/uploadResume.do", method = RequestMethod.GET)
    public String uploadResume(HttpServletRequest request, String recommendid,
                               String resid, ModelMap model) {
        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (StringUtils.isEmpty(openid)) {
            logger.debug("openid is null");
            return "wechat/headhunter/errorpage";
        }
        UserInfo user = userDAO.getByOpenId(openid);
        if (user == null) {
            logger.info("the openid=" + openid + " is not subscribed");
            return "wechat/headhunter/errorpage";
        }
        Hunter hunter = hunterDAO.getByActivateHunter(openid);
        if (hunter == null) {
            // todo: 信息提示尚未注册认证，但不用继续
            /*
             * Hunter newItem = new Hunter(); newItem.setOpenid(openid) ;
             * model.addAttribute("hunter", newItem); return
             * "wechat/headhunter/hunter/lietouxinxi1";
             */
            model.addAttribute("msg", "你尚未注册我们的服务。");
            model.addAttribute("url", "wechat/hunter/main.page");
            return "wechat/headhunter/msgpage";
        }

        // update person info
        Recommendation recommend = recommendDAO.getById(recommendid);
        recommend.setResid(resid);
        recommend.setResstatus(1); // 1表示在远程微信服务器上，需要下载自己的服务器
        recommendDAO.update(recommend);

        // String realPath =
        // request.getSession().getServletContext().getRealPath("/resources/images/resume");
        String realPath = FileController.BASE_PATH;
        String token = sysConfigService.getAccessToken();
        MediaAPI.getMediaFromWechat(realPath, resid, token);

        /* */
        String ticket = sysConfigService.getJsTicket();
        logger.debug("js api ticket is " + ticket);
        String url = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(request.getQueryString())) {
            url = url + "?" + request.getQueryString();
        }
        logger.debug("request url is " + url);

        Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

        jsConfig config = new jsConfig();
        config.setAppid(WebchatServiceConstant.APPID);
        config.setCurrenttimestamp(jsconfig.get("timestamp"));
        config.setNonceStr(jsconfig.get("nonceStr"));
        config.setSignatureStr(jsconfig.get("signature"));

        model.addAttribute("config", config);
        /* */

        model.addAttribute("resume", resid);

        return "wechat/headhunter/recommend/tuijianqueren";
    }

    // 推荐流程
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/recommend/help.page", method = RequestMethod.GET)
    public String helpOnline(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/tuijianliucheng";
    }

    // 错误页面
    @OAuthRequired
    @RequestMapping(value = "wechat/headhunter/error.page", method = RequestMethod.GET)
    public String errorPage(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/errorpage";
    }

    // 服务分享页面
    // @OAuthRequired
    @RequestMapping(value = "wechat/hunter/shareservice.page", method = RequestMethod.GET)
    public String shareservicePage(HttpServletRequest request, ModelMap model) {
        return "wechat/headhunter/shareservicepage";
    }

    // 职位分享页面
    // @OAuthRequired
    @RequestMapping(value = "wechat/hunter/sharejob.page", method = RequestMethod.GET)
    public String sharejobPage(HttpServletRequest request, int jobid,
                               ModelMap model) {

        HttpSession session = request.getSession();

        String openid = (String) session.getAttribute("OpenId");
        logger.debug("openid is " + openid);
        if (!StringUtils.isEmpty(openid)) {

            model.addAttribute("openid", openid);

            UserInfo user = userDAO.getByOpenId(openid);
            if (user != null) {

                Hunter hunter = hunterDAO.getByActivateHunter(openid);
                if (hunter != null) {
                    model.addAttribute("hunter", hunter);
                }

                Employer employer = employerDAO.getByOpenId(openid);
                if (employer != null) {
                    model.addAttribute("employer", employer);
                }

                JobDesc job = jobDAO.getById(jobid);
                if (job == null) {
                    logger.info("invalid Job id " + jobid);
                    model.addAttribute("msg", "该职位不存在或者已经过期。");
                }

                int companyId = job.getCompanyId();
                int cityId = job.getCityId();
                Company company = companyDAO.getById(companyId);
                City city = cityDAO.getById(cityId);

                Company expCompany = companyDAO.getById(job
                        .getExpectcompanyid());

                job.setCity(city);
                job.setCompanyName(company.getName());
                long data = job.getExpiredDate();
                job.setExpiredDateStr(DateUtil.getDateStr(data));
                model.addAttribute("job", job);
                model.addAttribute("expcompany", expCompany);
            }

        }

        return "wechat/headhunter/sharejobpage";
    }

    /*
     * // 职位明细 //@OAuthRequired
     *
     * @RequestMapping(value = "wechat/headhunter/recommend/toView2.do", method
     * = RequestMethod.GET) public String searchJobsDetail(HttpServletRequest
     * request, long jobid, ModelMap model) { Map<String, Object> returnMap =
     * new HashMap<String, Object>(); HttpSession session =
     * request.getSession(); String openid = (String)
     * session.getAttribute("OpenId");
     *
     * logger.debug("openid is " + openid); if (StringUtils.isEmpty(openid)) {
     * logger.error("openid is null"); return "wechat/headhunter/errorpage"; }
     * Hunter hunter = hunterDAO.getByOpenId(openid); if(hunter == null) {
     * logger.error(openid +" did not bind the employer/hunter"); return
     * "wechat/headhunter/errorpage"; }
     *
     * JobDesc job = jobDAO.getById(jobid); List<Recommendation> list = null;
     * //recommendDAO.getByJobandPerson(jobid, hunter.getId());
     *
     * returnMap.put("Recommends", list); returnMap.put("Job", job); return
     * "wechat/headhunter/zhiweixiangxixinxi"; }
     */

    // 职位候选人信息
    @RequestMapping(value = "wechat/recommend/toView.do", method = RequestMethod.GET)
    public String recommendtoView(HttpServletRequest request, Integer jobid, Integer createBy, Integer personId,
                                  ModelMap model) {

        List<RecommendedPerson> list = recommendDAO
                .getRecommendedPersons(2, createBy,
                        jobid, personId, 0);
        for (RecommendedPerson recommendedPerson : list) {
            if (!StringUtils.isEmpty(recommendedPerson.getCityId())) {
                City city = cityDAO.getById(Integer.parseInt(recommendedPerson.getCityId()));
                recommendedPerson.setCityName(city.getName());
            }
        }
        JobDesc job = jobDAO.getById(jobid);
        Company company = companyDAO.getById(job.getCompanyId());

        model.addAttribute("job", job);
        model.addAttribute("recommends", list);
        model.addAttribute("company", company);

        return "wechat/headhunter/zhiweihouxuanrenliebiao";
    }

    @RequestMapping("wechat/recommend/updateRemark")
    public @ResponseBody Map<String, Object> updateRemark(String recommendid,Integer personId,String remark) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Recommendation recommendation = recommendDAO.getById(recommendid);
        int row = recommendDAO.updateRemark(recommendid,remark);

        Person person = personDAO.getById(personId);
        JobDesc jobDesc = jobDAO.getById(recommendation.getJobId());
        Company company = companyDAO.getById(jobDesc.getCompanyId());
        String content = "";
        if("不合适".equals(remark)){
            content = person.getName()+", 您好！感谢您关注投递"+company.getName()+"," +
                    "很遗憾的通知您未通过["+jobDesc.getName()+"]职位的评估，已将您的简历储备到我司人才库中，后续如有合适职位，我们将会优先与您联系。再次感谢您对我们的关注！";
        }else{
            content = "你的简历已经通过初筛，HR会在近期与你沟通，请保持联系方式畅通，非常感谢你对我们的支持，请耐心等待！";

        }
        logger.info("==============>发送短信给候选人,短信内容是:{}", content);
        SMSService.sendAskMsg(person.getPhone(),content);
        returnMap.put("errorcode",0);
        return returnMap;
    }
}
